#include <fstream>
#include <iostream>
#include <sstream>

/* __________________________ SML library ________ */
#include "../inc/segment.h"
#include "../inc/trackball.h"
#include "../inc/segmenttree.h"
#include "../inc/link.h"
#include "../inc/brain.h"

#include "../inc/plan.h"

int main ( int _argc, char** _argv )
{
	int cpt = 0;
	
	vector<double> rsltX;
	vector<double> rsltY;
	vector<double> rsltZ;
	
	Map tpdX;
	Map tpdY;
	Map tpdZ;
	Map tpd;
	
	Mesh mesh;
	
	SegmentTree* sulciTPD = new SegmentTree();
	SegmentTree* sulciTPDX = new SegmentTree();
	SegmentTree* sulciTPDY = new SegmentTree();
	SegmentTree* sulciTPDZ = new SegmentTree();
	
	
	
	
	
	
	
	
	cout<<"/* ____________________ Loading and initializing the mesh _____ */"<<endl;
	mesh.loadOBJ( _argv[1] );																/* Loading the source mesh. */
	mesh.computeNormals();																	/* Computing its normals. */
	mesh.normalize();																		/* Resize it to a unit length box. */
	
	cout<<"/* ____________________ Computing the maps _____ */"<<endl;
	tpd = mesh.tpd( 5 );
	tpdX = mesh.tpd ( 5, Vector3D(1,0,0));
	tpdY = mesh.tpd ( 5, Vector3D(0,1,0));
	tpdZ = mesh.tpd ( 5, Vector3D(0,0,1));
	
	cout<<"/* ____________________ Creating sulci tree _____ */"<<endl;
	sulciTPD->createFromMap( LESSER_EQUAL, -20, mesh, tpd );
	sulciTPD = SegmentTree::filterArea( &mesh, sulciTPD, 0.2 );
	
	cout<<"/* ____________________ Computing the orientation index _____ */"<<endl;
	for ( SegmentTree* it = sulciTPD ; it != NULL ; it = it->getBrother() )
	{
		rsltX.push_back(0);
		rsltY.push_back(0);
		rsltZ.push_back(0);
		
		for ( list<Vertex*>::iterator vert = it->getSegment()->getBegin() ; vert != it->getSegment()->getEnd() ; ++vert )
		{
			rsltX[cpt] += tpdX.getIData( (*vert)->getID() );
			rsltY[cpt] += tpdY.getIData( (*vert)->getID() );
			rsltZ[cpt] += tpdZ.getIData( (*vert)->getID() );
		}
		
		rsltX[cpt] /= it->getSegment()->getVerts().size();
		rsltY[cpt] /= it->getSegment()->getVerts().size();
		rsltZ[cpt] /= it->getSegment()->getVerts().size();
		
		cpt++;
	}
	
	cout<<"/* ____________________ Writing the results _____ */"<<endl;
	
	ofstream file ( _argv[2] );
	
	if ( ! file.is_open() )
	{
		cout<<"Erreur lors de l'ouverture/creation de \""<<_argv[2]<<"\""<<endl;
		return -1;
	}
	
	else
	{
		for ( int i = 0 ; i < (int)rsltX.size() ; i++ )
		{
			file<<rsltX[i]<<" "<<rsltY[i]<<" "<<rsltZ[i]<<endl;
		}
	}
	
	return 0;
}
